package org.demo.zookeeper;

import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.Revoker;
import org.apache.curator.retry.ExponentialBackoffRetry;

public class LockTest {

	static ExecutorService service = Executors.newFixedThreadPool(10);
	static ConcurrentHashMap<String, CuratorFramework>  map = new ConcurrentHashMap<String, CuratorFramework>(2);
	private static final String PATH = "/examples/locks";
	
	public static void main(String[] args) {
		
		 for (int i = 1; i < 3; ++i) {
			 
			 final int index = i;
			 
			  service.submit(new Callable<Void>() {

				@Override
				public Void call() throws Exception {
					
					CuratorFramework client = CuratorFrameworkFactory.builder()
							.connectString("192.168.70.30:2181") // 服务器列表
							.sessionTimeoutMs(5000) // 会话超时时间，单位毫秒
							.connectionTimeoutMs(3000) // 连接创建超时时间，单位毫秒
							.retryPolicy(new ExponentialBackoffRetry(1000, 3)) // 重试策略
							.build();
					client.start();
					System.out.println("Client."+index+"="+client);
					map.put("Client."+index, client);
					
					DistributedLock distributedLock = new  DistributedLock(client, PATH,"Client."+index);
				
					
					System.out.println("Client."+index+"进入");
					distributedLock.lock();
					
					System.out.println("Client."+index+"等待");
					
					if(index==1){
						Thread.sleep(5000);
					}
					distributedLock.unlock();
					System.out.println("Client."+index+"解锁");
					return null;
				}
			});
		  }
		 
		 
		 
		 service.submit(new Callable<Void>() {
			@Override
			public Void call() throws Exception {
				Thread.sleep(2000);
//				如果你请求撤销当前的锁， 调用Revoker方法。
				System.out.println("撤回Client.1");
				Revoker.attemptRevoke(map.get("Client.1"), PATH);
				
				return null;
			}

			
		});
		 

		 
		 service.shutdown();
	}
}
